<template>
  <section style="height:100%">
    <el-row style="height:100%" class="login-ct">
      <el-col :span="24">
        <div class="logo clear">
          <img src="../assets/logo.png">
        </div>
      </el-col>
      <el-col :span="24" class="ct">
        <el-form :model="ruleForm2"
                 :rules="rules2"
                 ref="ruleForm2"
                 label-position="left"
                 label-width="0px"
                 class="demo-ruleForm card-box loginform"
                 v-loading="fullscreenLoading"
                 element-loading-text="拼命加载中">
          <h3 class="title">华星光电大数据平台</h3>
          <el-form-item prop="account" style="height: 36px;">
            <el-input type="text" v-model="ruleForm2.account" auto-complete="off"
                      placeholder="账号"></el-input>
          </el-form-item>
          <el-form-item prop="checkPass" style="height: 36px;">
            <el-input type="password"
                      v-model="ruleForm2.checkPass"
                      auto-complete="off"
                      placeholder="密码"></el-input>
          </el-form-item>

          <el-form-item v-if="upDatepw" prop="nCheckPass" style="height: 36px;">
            <el-input type="password"
                      v-model="ruleForm2.nCheckPass"
                      auto-complete="off"
                      placeholder="新密码"></el-input>
          </el-form-item>
          <el-form-item v-if="upDatepw" prop="nCheckPass2" style="height: 36px;">
            <el-input type="password"
                      v-model="ruleForm2.nCheckPass2"
                      auto-complete="off"
                      placeholder="重复新密码"></el-input>
          </el-form-item>

          <!-- <el-form-item v-if="!upDatepw" prop="captcha" >
            <el-row>
              <el-col :span="12">
                <el-input type="text"
                    v-model="ruleForm2.captcha"
                    placeholder="验证码"></el-input>
              </el-col>
              <el-col :span="12" style="text-align: center;">
                <img :src="imgData" alt="" @click ="getCaptcha" style="height: 35px;padding-left: 30px;">
              </el-col>
            </el-row>
          </el-form-item> -->
          <el-checkbox v-if="!upDatepw" v-model="checked"
                       checked style="margin:0px 0px 35px 0px;">记住密码
          </el-checkbox>
          <el-form-item style="width:100%;">
            <el-button v-if="!upDatepw" type="primary"
                       style="width:100%;"
                       @click.native.prevent="handleSubmit2">登录
            </el-button>

            <el-button v-if="upDatepw" type="primary"
                       style="width:100%;"
                       @click.native.prevent="upPWSubmit">修改密码
            </el-button>

            <!--<el-button @click.native.prevent="handleReset2">重置</el-button>-->
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <div class="bottomTips">
      Copyright © 2015 深圳市华星光电技术有限公司
    </div>
  </section>
</template>

<script>
  import dao from '../common/dao'
  import util from '../common/util'
  import {mapActions} from 'vuex'
  import NProgress from 'nprogress'

  export default {
    data() {
      return {
        fullscreenLoading: false,
        query: {},
        imgData:null,
        upDatepw:false,
        ruleForm2: {
          account: 'admin',
          checkPass: 'admin',

          captcha:'',
          cid:'',
          nCheckPass:'',
          nCheckPass2:'',
        },
        rules2: {
          account: [
            {required: true, message: '请输入账号', trigger: 'blur'},
            //{ validator: validaePass }
          ],
          checkPass: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            //{ validator: validaePass2 }
          ],
          nCheckPass: [
            {required: true, message: '请输入新密码', trigger: 'blur'},
            {
              validator: (rule, value, callback, source, options) => {
                if (value == this.ruleForm2.checkPass) callback(new Error('不能与原密码一致!'));
                else callback()
              }, trigger: 'blur'
            },
           {validator: util.validatePWS, trigger: 'blur'}
          ],
          nCheckPass2: [
            {required: true, message: '请输入新密码', trigger: 'blur'},
            { validator:  (rule, value, callback) => {
              if (value != this.ruleForm2.nCheckPass) callback(new Error('新密码不一致'));
              else callback();
            }, trigger: 'blur' }
          ],
          captcha:[
            {required: true, message: '请输入验证码', trigger: 'blur'},
          ]
        },
        checked: true
      };
    },
    methods: {
      ...mapActions([
        'setUser', // 映射 this.setuser() 为 this.$store.dispatch('setuser')
        'resetAll'
      ]),
      handleReset2() {
        this.$refs.ruleForm2.resetFields();
      },
      saveInfo(res){
        let _this = this;
        util.save('token', res.body.token.replace(/[\r\n]/g, ''));
        util.save('user_id', res.body.user_id);
        util.save('user_name', res.body.user_name);
        util.save('user_type', res.body.user_type);

        this.resetAll().then(() => {
          this.setUser({user_name: res.body.user_name, user_id: res.body.user_id, user_type: res.body.user_type});
          this.saveCheckPass();
          this.$notify({
            title: '成功',
            message: '登录成功!',
            type: 'success'
          });
          _this.fullscreenLoading = false;
          _this.$router.replace('/page11');
        })
      },
      upPWSubmit(){
        this.$refs.ruleForm2.validate((valid) => {
            if (!valid) {return false}
            console.log(123)

            dao.expireUpdatePasswd({
              user_name:this.ruleForm2.account,
              password_old:util.rsaEncryption(this.ruleForm2.checkPass),
              passworVerify:util.rsaEncryption(this.ruleForm2.nCheckPass),
              password:util.rsaEncryption(this.ruleForm2.nCheckPass2),
            }).then(res=>{
              if(res.FX.err) return false;
              this.$notify.success({
                title: '成功',
                message: '修改成功，请重新登录',
              });
              this.upDatepw = false;

              this.ruleForm2.checkPass = ""
              this.ruleForm2.account = ""

            })


        })
      },
      handleSubmit2(ev) {
        this.$refs.ruleForm2.validate((valid) => {
          if (!valid) {return false}
          //_this.$router.push('/table');
          util.restoreSystem()
          dao.login({
            user_name: this.ruleForm2.account,
            captcha: this.ruleForm2.captcha,
            cid: this.ruleForm2.cid,
            password: util.rsaEncryption(this.ruleForm2.checkPass)
          }).then((res) => {
            // this.getCaptcha()
            if (res.body.retCode == "200") {
              this.saveInfo(res)
              if(res.body.password_expire_prompt && res.body.password_expire_prompt != ""){
                this.$notify({
                  title: '警告',
                  message: `${res.body.password_expire_prompt}`,
                  type: 'warning',
                  offset: 100
                });
              }
            } else {
              if(res.body.is_password_expire == 0){
                this.upDatepw = true
                this.ruleForm2.checkPass = ""
                this.ruleForm2.account = ""
                this.ruleForm2.nCheckPass = ""
                this.ruleForm2.nCheckPass2 = ""
              }
            }

            /*
              _this.$router.replace('/page11');
            })*/
          }).catch(res => {
            // this.$message.error('登录失败!');
          });
          //_this.$router.replace('/page11');

        });
      },
      saveCheckPass(){
        if (this.checked) {
          util.save('checkPass', this.ruleForm2.checkPass);
        }
        else {
          util.save('checkPass', "");
        }
      },
      getCheckPass(){
        this.ruleForm2.account = util.fetch("user_name") || "";
        this.ruleForm2.checkPass = util.fetch("checkPass") || "";
      },
      errCss(){
        let d = document.querySelectorAll('.el-form-item__content');
        for (let i = 0; i < d.length; i++) {
          d[i].style.height = "36px";
        }
      },

      enterKeyDown () { //回车键登录事件

        document.querySelector(".login-ct").querySelector('.el-input__inner').focus();

        let login = (event) => {
          var e = event || window.event || arguments.callee.caller.arguments[0];
          if (e && e.keyCode == 13) { // enter 键
            window.event.cancelBubble = true;
            this.handleSubmit2();
          }
        }

        let input = document.querySelector(".login-ct").querySelectorAll('.el-input__inner') || [];
        for (let i = 0; i < input.length; i++) {
          input[i].addEventListener("keydown", login);
        }

      },
      getCaptcha(){

        dao.captcha({cid:this.ruleForm2.cid}).then(res=>{
          this.ruleForm2.cid = res.headers.get('Pragma') || ''
          this.imgData = URL.createObjectURL(res.bodyBlob)
        })
      },
      pageInit(){
        if (this.query.Token) {
          this.fullscreenLoading = true
          let fourToken = this.query.Token
          dao.login({fourToken}).then(res=>{

            if(res.FX.err) return false
            this.saveInfo(res)
          })
        } else {
          // this.getCaptcha();
          this.getCheckPass();
          this.errCss();
          this.enterKeyDown();
        }
      }
    },
    mounted () {
      this.query = this.$store.state.route.query || {};
      this.pageInit()
    },

  }
</script>

<style scoped>
  .ct {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .logo-title {
    padding-left: 10px;
  }

  .logo {
    position: absolute;
    top: 0;
    letf: 0;
    padding: 20px 0 0 20px;
  }

  .logo img {
    width: 100px;
  }

  .panel-top {
    position: absolute;
    height: 60px;
    line-height: 60px;
    background: #fff;
    color: #51ace3;
  }

  .login-ct {
    height: 100%;
    background-image: url(../assets/1.jpg);
    background-repeat: no-repeat;
    background-position: center;
    background-attachment: fixed;
    background-size: cover
  }

  .card-box {
    width: 400px;
    /*height: 270px;*/
    padding: 20px;
    border-radius: 5px;
    background-color: #fff;
    background-clip: padding-box;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    box-shadow: 0 0px 8px 0 rgba(0, 0, 0, 0.06), 0 1px 0px 0 rgba(0, 0, 0, 0.02);
  }

  .title {
    margin: 0px auto 40px auto;
    text-align: center;
    font-size: 18px;
    color: #666;
  }

  .loginform {
    width: 260px;
    padding: 35px 20px 15px 20px;
  }

  .bottomTips {
    position: absolute;
    bottom: 5px;
    width: 100%;
    font-size: 12px;
    line-height: 2;
    color: #aaa;
    text-align: center;
  }

  .el-form-item.is-required {
    height: 36px;
  }

  .el-form-item__error {
    top: 36px !important;
  }
</style>